<?php
//TCP client
class Lib_Request_TcpClient{
    private static $obj = null;
    private $client = null;
    private $config = array();

    /**
     * 封闭构造
     */
    private function __construct(){
        $env = getenv('RUNTIME_ENVIROMENT') ? getenv('RUNTIME_ENVIROMENT') : (defined('SHELL_VARIABLE') ? SHELL_VARIABLE : '');
        $env = empty($env) ? 'local' : $env;
        $config = require_once LIBRARY_DIR . '/Conf/' . $env . '/swoole.php';
        $this->config = $config['task'];
        $this->client = new swoole_client(SWOOLE_SOCK_TCP);
    }

    /**
     * 单例获取
     * @return Lib_Request_TcpClient
     */
    public static function getInstance(){
        if(is_null(self::$obj)){
            self::$obj = new self();
        }
        return self::$obj;
    }

    public function singleSend($task_data){
        $this->client->connect($this->config['host'], $this->config['port'], 0.5);
        if(is_array($task_data)){
            $task_data = json_encode($task_data) . PHP_EOL;
        }
        $res = $this->client->send($task_data);
        $this->client->close();
        return $res;
    }

    public function realtimeSend($task_data){

        $this->client->connect($this->config['host'], $this->config['port'], 30);
        if(is_array($task_data)){
            $task_data = json_encode($task_data) . PHP_EOL;
        }else{
            $task_data = $task_data . PHP_EOL;
        }
        $this->client->send($task_data);
        $res = $this->client->recv();
        $this->client->close();
        return $res;
    }

    public function batSend($tasks){
        $this->client->connect($this->config['host'], $this->config['port'], 0.5);
        foreach ($tasks as $key => $task){
            if($key % 10 == 0 ){
                sleep(0.5);
            }
            if(is_array($task)){
                $task_data = json_encode($task) . PHP_EOL;
                $res[] = $this->client->send($task_data);
            }
        }
        $this->client->close();
        return $res;
    }
}
?>